from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from ..translator.pdf_translator import PDFTranslator
from ..model import DeepSeekModel  # 根据实际模型调整
import tempfile
import os

app = FastAPI()

@app.post("/translate")
async def translate_pdf(
    file: UploadFile = File(...),
    target_language: str = "中文",
    file_format: str = "PDF",
    keep_layout: bool = True
):
    try:
        # 创建临时文件
        with tempfile.NamedTemporaryFile(delete=False) as tmp:
            tmp.write(await file.read())
            tmp_path = tmp.name
        
        # 初始化翻译器（需根据实际配置调整）
        # 修改模型初始化部分
        model = DeepSeekModel(
            model="deepseek-chat",  # 新增模型名称参数
            api_key='sk-fba5dfbe737e4e6681b52280e60e90c1'
        )
        translator = PDFTranslator(model)
        
        # 执行翻译
        output_path = f"{os.path.splitext(tmp_path)[0]}_translated.{file_format.lower()}"
        for progress in translator.translate_pdf(
            tmp_path,
            file_format=file_format,
            target_language=target_language,
            output_file_path=output_path,
            keep_layout=keep_layout
        ):
            # 可添加进度推送逻辑
            pass
        
        return JSONResponse({
            "status": "completed",
            "output_path": output_path
        })
    
    except Exception as e:
        return JSONResponse(
            {"error": str(e)},
            status_code=500
        )


# 新增启动代码
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("ai_translator.api.server:app", host="0.0.0.0", port=8000, reload=True)